/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.se2.meteocal.control;

import it.polimi.se2.meteocal.entity.Location;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
/**
 *
 * @author Ugo
 */
@Stateless
public class LocationManager {
   
    @PersistenceContext
    public EntityManager em;
    
    public void create(Location entity) {
        if(newLocation(entity.getLocation()))
            em.persist(entity);
    }

    public void edit(Location entity) {
        em.merge(entity);
    }

    public void remove(Location entity) {
        em.remove(em.merge(entity));
    }
    
    public boolean newLocation(String location) {
        try{
            em.createNamedQuery(Location.CountByLocation, Location.class)
                .setParameter("location", location)
                .getSingleResult();
            
        }
        catch(NoResultException e){
            return true;
        }
         return false;
    }
     
    public List<Location> getAllLocation() {
        return em.createNamedQuery(Location.findAll,Location.class).getResultList();        
    }
    
}